<template>
    <div 
        class="chart-box"
        ref="chartRef"
        :option="option"
        >
    </div>
</template>
<script lang="ts" setup>
//引入echarts模块
import { ECharts, init } from 'echarts';

//父组件传值
const props = defineProps({
	chartObject: {
		type: Object,
		default: () => {
			return {
				legend: [],
				xData: [],
				series: []
			};
		}
	}
})
//图表ref
const chartRef = ref<HTMLDivElement>();
let myChart: ECharts;
let timer: any;
let option = reactive({});

//初始化options
const initOption = () => {
	let serieList:any = [];
	props.chartObject.series.forEach((item:any) => {
		serieList.push({
			name: item.name,
			type: item.type,
			barWidth: '30%',
			data: item.data,
			itemStyle: {
				color: {
					type: 'linear',
					x: 0, // 右
					y: 1, // 下
					x2: 0, // 左
					y2: 0, // 上
					colorStops: [
						{
							offset: 0,
							color: '#F89898' // 0% 处的颜色
						},
						{
							offset: 1,
							color: '#F56C6C' // 100% 处的颜色
						}
					]
				}
			}
		});
	});
	option = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow',
				label: {
					show: true
				}
			}
		},
		grid: {
			left: '4%',
			top: '8%',
			right: '2%',
			bottom: '5%'
		},
		legend: {
			data: props.chartObject.legend,
			top: '4%',
			color: '#1FC3CE',
			fontSize: 14,
		},
		xAxis: {
			data: props.chartObject.xData,
			axisLine: {
				show: true, //隐藏X轴轴线
				lineStyle: {
					color: '#eee',
					width: 1
				}
			},
			axisTick: {
				show: true, //隐藏X轴刻度
				alignWithLabel: true
			},
			axisLabel: {
				show: true,
				color: '#333', //X轴文字颜色
				fontSize: 14
			}
		},
		yAxis: [
			{
				type: 'value',
				nameTextStyle: {
					color: '#333',
					fontSize: 14
				},
				splitLine: {
					show: true,
					lineStyle: {
						width: 1,
						color: '#eee'
					}
				},
				axisTick: {
					show: false
				},
				axisLine: {
					show: false
				},
				axisLabel: {
					show: true,
					color: '#333',
					fontSize: 14
				}
			}
		],
		series: serieList
	}
}
//初始化echarts
const initChart = ():void => {
    if(myChart !== undefined) {
        myChart.dispose();
    }
    initOption();
    myChart = init(chartRef.value as HTMLDivElement);
    //渲染echarts
    myChart?.setOption(option, true);
}

//重新渲染echarts
const resizeChart = ():void => {
    timer = setTimeout(() => {
        if(myChart !== undefined) {
            myChart.resize();
        }
    }, 500);
}

//初始化
const initPage = ():void => {
    initChart();
    window.addEventListener('resize', resizeChart);
}

//销毁
const destroyPage = ():void => {
    window.removeEventListener('resize', resizeChart);
    timer && clearTimeout(timer);
}

onMounted(() => {
    initPage();
});

onBeforeMount(() => {
    destroyPage();
})

watch(
    config.chartObject,
    () => {
        initChart();
    },
    {
        deep: true
    }
)

</script>
<style scoped>
.chart-box {
    width: 100%;
    height: 100%;
}
</style>